package com.ruoyi.web.controller.system;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysUnit;
import com.ruoyi.system.domain.SysWord;
import com.ruoyi.system.mapper.SysWordMapper;
import com.ruoyi.system.service.ISysWordService;

/**
 * 单词管理 控制层
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/word")
public class SysWordController extends BaseController
{
    @Autowired
    private ISysWordService sysWordService;
    @Autowired
    private SysWordMapper sysWordMapper;

    /**
     * 获取列表
     */
    @PreAuthorize("@ss.hasPermi('system:word:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysWord sysWord,
    		Integer lev, Long id) {
    	// 根据节点加载数据
    	if (id != null) {
			if (lev == 1) {
				sysWord.setTextbookId(id);
			} else if (lev == 2) {
				sysWord.setCourseId(id);
			} else if (lev == 3) {
				sysWord.setUnitId(id);
			}
		}
        startPage();
        List<SysWord> list = sysWordService.selectList(sysWord);
        
        // 更新单词的mp3文件
        {
			Thread t = new Thread(() -> {
				// 单词自动下载mp3机制
				String serverUrl = RuoYiConfig.getServerUrl();
				if (!serverUrl.contains("localhost")) {
			        List<SysWord> listNoAudio = sysWordMapper.listNoAudio();
					for(SysWord e : listNoAudio) {
						Long wordId = e.getWordId();
						String text = e.getWordName();
						System.out.println("word_id---" + e.getWordId() + ",word---" + text);
						sysWordService.convertTextToMp3(wordId, text);
					}
				}
			});
			t.start();
        }
        
        return getDataTable(list);
    }

    /**
     * 根据ID获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:word:query')")
    @GetMapping(value = "/{wordId}")
    public AjaxResult getInfo(@PathVariable Long wordId)
    {
        return success(sysWordService.selectById(wordId));
    }

    /**
     * 新增
     */
    @PreAuthorize("@ss.hasPermi('system:word:add')")
    @Log(title = "单词管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysWord sysWord)
    {

        sysWord.setCreateBy(getUsername());
        String wordName = sysWord.getWordName();
        if (wordName == null || wordName.length() == 0) {
			return AjaxResult.error("单词名称不能为空");
		}
        
        if (sysWordMapper.countByWordName(wordName) > 0) {
			return AjaxResult.error("单词已存在，不能重复添加");
		}
        
        return toAjax(sysWordService.insert(sysWord));
    }

    /**
     * 修改
     */
    @PreAuthorize("@ss.hasPermi('system:word:edit')")
    @Log(title = "单词管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysWord entity)
    {
        entity.setUpdateBy(getUsername());
        return toAjax(sysWordService.update(entity));
    }

    /**
     * 删除
     */
    @PreAuthorize("@ss.hasPermi('system:word:remove')")
    @Log(title = "单词管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{wordIds}")
    public AjaxResult remove(@PathVariable Long[] wordIds)
    {
        return toAjax(sysWordService.deleteByIds(wordIds));
    }

    @Log(title = "单词管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:word:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysWord entity)
    {
        List<SysWord> list = sysWordService.selectList(entity);
        ExcelUtil<SysWord> util = new ExcelUtil<SysWord>(SysWord.class);
        util.exportExcel(response, list, "单词数据");
    }

    /**
     * 查询已分配该班级的学员列表
     */
    @PreAuthorize("@ss.hasPermi('system:word:list')")
    @GetMapping("/listAllWord")
    public TableDataInfo listAllWord()
    {
        List<SysWord> list = sysWordService.listAll();
        return getDataTable(list);
    }

    /**
     * 查询未分配该班级的学员列表
     */
    @PreAuthorize("@ss.hasPermi('system:word:list')")
    @GetMapping("/listSelected/{unitId}")
    public TableDataInfo listSelected(@PathVariable("unitId") Long unitId)
    {
        List<SysWord> list = sysWordService.listSelected(unitId);
        return getDataTable(list);
    }

    @Log(title = "单词管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:word:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport, String courseType) throws Exception
    {
        ExcelUtil<SysWord> util = new ExcelUtil<SysWord>(SysWord.class);
        List<SysWord> dataList = util.importExcel(file.getInputStream());
        String message = sysWordService.importData(dataList);
        return success(message);
    }

    /**
     * 获取单元树列表
     */
    @PreAuthorize("@ss.hasPermi('system:word:list')")
    @GetMapping("/unitTree")
    public AjaxResult unitTree(SysUnit sysUnit)
    {
        return success(sysWordService.selectUnitTreeList(sysUnit));
    }
}